using System.Collections.Generic;
using System.Linq;
using Android.Graphics;
using Android.Text;
using Android.Util;
using Android.Views;
using Android.Widget;
using mb.Droid;

namespace libmp
{
    class SearchResultView : ExMovieList
    {
        public static void OpenSearchResult(string keyword)
        {
            logger.Log("open search", keyword);
            if (keyword == "") return;

            var ctx = StartActivity.This;
            var mfrag = new SearchResultView(keyword).CreateFragment();
            var ft = ctx.SupportFragmentManager.BeginTransaction();
            var id = ctx.ContentViewId;
            ft.Replace(id, mfrag);
            ft.AddToBackStack("Search");
            ft.Commit();
        }

        MyFragment myFragment;
        LinearLayout rootLayout;
        string keyword;

        public SearchResultView(string kw)
        {
            keyword = kw;
            ReloadData();

        }

        public MyFragment CreateFragment()
        {
            myFragment = new MyFragment()
            {
                Hold = 0,
                    MyOnCreateView = (f, container) => { return CreateView(); },
                    MyOnReEnter = f => { ReloadData(); }
            };
            return myFragment;
        }

        public View CreateView()
        {
            if (rootLayout != null) return rootLayout;

            LinearLayout layout = new LinearLayout(activity);
            layout.Orientation = Orientation.Vertical;
            layout.SetBackgroundColor(Util.MainBKColor);
            layout.FillParent();
            layout.AddView(CreateTitleBar());
            layout.AddView(new LinearLayout(activity) { LayoutParameters = new ViewGroup.LayoutParams(-1, 10) });

            Setup();
            Reload();

            layout.AddView(GetListView());
            return rootLayout = layout;
        }

        void ReloadData()
        {
            dataSource = DataStore.store.GetAllVideo().Where(vi => vi.vname.IndexOf(keyword) >= 0).ToList();
            adapter?.NotifyDataSetChanged();
        }

        View CreateTitleBar()
        {
            return Common.CreateTitleBar(new Common.TitleBarOption()
            {
                Title = "搜索",
            });
        }

        protected override void UpdateCell(View cell, int p, Dictionary<string, object> viewData)
        {
            base.UpdateCell(cell, p, viewData);
            int idx = GetDataIndex(p);
            var hname = dataSource[idx].vname.Replace(keyword, $"<b><font color='red'>{keyword}</font></b>");
            var sps = Html.FromHtml(hname);
            var tv = viewData["text"] as TextView;
            tv.TextFormatted = sps;
        }
    }
}